<?php
/*
 * SiteController.php
 * Classe controller des Sites
 */

namespace RHX\Controller;

use RHX\Model\Object\Site;
use RHX\Model\Object\SiteHoraire;
use RHX\Helper\Uploader;
use RHX\Model\Object\SiteDoc;
use Zend\View\Model\JsonModel;

/**
 * Classe Site
 */
class SiteController extends RHXController {

    /**
     * Page d'accueil des Sites
     *
     * @return array
     */
    public function indexAction() {
       
	return array();
    }

    /**
     * Liste des Sites par Ajax
     * 
     * @return array
     */
    public function loadIndexAction() {
	// Changement de Layout
	$this->layout('layout/ajax');

	// Variables paramètres
	$page = $this->params()
		->fromRoute('id', 1);

	// Tables
	$siteTable = $this->getService('Table\SiteTable');

	// Liste des Sites
	$siteList = $siteTable->getSites('libelle ASC', $page, 100);

	return array(
	    'siteList' => $siteList,
	);
    }

    /**
     * Ajouter un nouveau Site
     * 
     * @return array
     */
    public function addNewAction() {
	// Changement de Layout
	$this->layout('layout/ajax');

	// Variables en POST
	$post = $this->getRequest()
		->getPost();

	// Tables
	$siteTable = $this->getService('Table\SiteTable');

	// Traitement des Informations
	$site	 = new Site($post);
	$siteTable->save($site);

	return array(
	    'newSite' => $site,
	);
    }
    /* Ajout de nouveau site
     * 
     * @return array
     */
    public function addNewExAction(){
        //config 
        $config = $this->getServiceLocator()->get('config');        
        $repPhoto = $config['upload_directory']['site']['photo'];
        $repRib = $config['upload_directory']['site']['rib'];
        
        // table 
        $horTbl = $this->getService('Table\SiteHoraireTable');
        
        $query = $this->getRequest();
        $ret = array();
        
        if ($query->isPost()) {
            $post = $query->getPost();
            
            $siteTbl = $this->getService('Table\SiteTable');
            // Traitement des Informations
            $site	 = new Site($post);
            $idSite = $siteTbl->save($site);
            $site->id = $idSite;
            
            // Fichiers uploadés
            // photo
            $photo = $site->photo;
            $dirPublic = $repPhoto;
            $dir = str_replace('public/', '', $dirPublic); 
            $newName = 'photo-' .$site->id. '.' . $post->photo_extension;
            if (@rename($dirPublic . $photo, $dirPublic . $newName)) {
                $site->photo = $newName;
            } elseif (@rename($dir . $photo, $dir . $newName)) {
                $site->photo = $newName;
            }
            
            // rib
            $rib = $site->rib;
            $dirPublic = $repRib;
            $dir = str_replace('public/', '', $dirPublic); 
            $newName = 'rib-' .$site->id. '.' . $post->rib_extension;
            if (@rename($dirPublic . $rib, $dirPublic . $newName)) {
                $site->rib = $newName;
            } elseif (@rename($dir . $rib, $dir . $newName)) {
                $site->rib = $newName;
            }
            
            // end Fichiers uploadés
            
            //saving site
            $siteTbl->save($site);
            
             // horaire
            $dataHor    = $post ['horaire']; 
            $dataHor ['id'] = 0;
            $dataHor ['site_id'] = $idSite;
            
            $hor        = new SiteHoraire($dataHor);
            $horTbl->save($hor);            
            //end horaire
            
            $ret['success'] = 'true';
            //return $ret;	
            return $this->redirect()
                        ->toRoute('RHX/default', array('controller' => 'site'));
        }
    }

    /**
     * Sauvegarder les données d'un Site
     *
     * @return array
     */
    public function saveAction() {
	// Changement de Layout
	$this->layout('layout/ajax');

	// Variables en POST
	$post = $this->getRequest()
		->getPost();

	// Tables
	$siteTable = $this->getService('Table\SiteTable');

	// Traitement des Informations
	$site = new Site($post);
	$siteTable->save($site);

	return array(
	    'editSite' => $site,
	);
    }

    /**
     * Effacer un Site
     * 
     * @return array
     */
    public function eraseAction() {
	// Changement de Layout
	$this->layout('layout/ajax');

	// Identifiant du Site
	$id = $this->params()
		->fromRoute('id', 0);

	// Table
	$siteTable = $this->getService('Table\SiteTable');

	// Traitement des informations
	$nb = $siteTable->erase($id);

	return array(
	    'id'	 => $id,
	    'nb'	 => $nb,
	);
    }

    /**
     * Edition des données d'un Site
     *
     * @return array
     */
    public function editDataAction() {
	// Changement de layout
	$this->layout('layout/ajax');

	// Données en POST
	$post = $this->getRequest()
		->getPost();

	// Variables
	$pk	 = $post->pk;
	$name	 = $post->name;
	$value	 = addslashes($post->value);
        
	// Adapter de la base de données
	$adapter = $this->getAdapter();

	// Requête SQL
	$sql	 = "UPDATE rh_site SET $name = '$value' WHERE id = $pk";
	$result	 = $adapter->query($sql)
		->execute();
        //\Zend\Debug\Debug::dump($sql);
	return array(
	    'sql'	 => $sql,
	    'result' => $result,
	);
    }
    
    /**
     * Edition des données nombre d'un Site
     *
     * @return array
     */
    public function editNumberDataAction() {
	// Changement de layout
	$this->layout('layout/ajax');

	// Données en POST
	$post = $this->getRequest()
		->getPost();

	// Variables
	$pk	 = $post->pk;
	$name	 = $post->name;
	$value	 = addslashes($post->value);
        
	// Adapter de la base de données
	$adapter = $this->getAdapter();

	// Requête SQL
	$sql	 = "UPDATE rh_site SET $name = $value WHERE id = $pk";
	$result	 = $adapter->query($sql)
		->execute();
        //\Zend\Debug\Debug::dump($sql);
	return array(
	    'sql'	 => $sql,
	    'result' => $result,
	);
    }
    
    public function deleteAction() {
	// Changement de layout
	$this->layout('layout/ajax');
	// table Site
	$tableSite	 = new \RHX\Model\Table\SiteTable($this->getAdapter());
	// POST
	$post		 = $this->getRequest()
		->getPost();
	// Effacement
	$result		 = array(
	    'done'	 => false,
	    'error'	 => null,
	);
	try {
	    $nb = $tableSite->erase($post->site);
	    if ($nb >= 1) {
		$result['done'] = true;
	    }
	}
	catch (\Exception $ex) {
	    $result['done']	 = false;
	    $result['error'] = $ex->getMessage();
	}

	return new \Zend\View\Model\JsonModel($result);
    }
    
    /**
     * rendu de la page d'edition des données d'un Site
     *
     * @return array
     */
     public function editAction() {
          
        //params
        $idSite = (int) $this->params()->fromRoute('id', 0);
         
        //config 
        $config = $this->getServiceLocator()->get('config');        
        $repUpload = $config['upload_directory']['site'];	
        
        // manager 
        $siteManager = new \RHX\Model\Manager\SiteManager($this->getAdapter());         
        
        // tables         
        $siteTable      = $this->getService('Table\SiteTable');
        $empTable   = $this->getService('Table\EmployeTable');
        $avTbl = $this->getService('Table\AvenantTable');
        $pstTbl = $this->getService('Table\PosteTable');
        $horTbl = $this->getService('Table\SiteHoraireTable');
            
        //site
        $site   = $siteTable->get($idSite);
        $idDir  =  $site ? $site->directeur_id : null;
        
        //Directeur du site
        if( $idDir ){            
            $oDir   =  $empTable->get($idDir);            
            
            $av = $avTbl->get($oDir->avenant_id);            
            $pst = $pstTbl->get($av->poste_id);            
            $oDir->infDir = $pst->code. ' - '.$oDir->nom1 . ' '. $oDir->prenom;
            
            $ret['directeur'] = $oDir;
        }
        
        // Horaire du site
        $horaire = $horTbl->getBySite($site->id);
        
        if(! $horaire ){ // if has hot yet horraire then create one
            //creating
            $dataHor['site_id']  = $site->id;
	    $dataHor['type']  = \RHX\Model\Object\SiteHoraireType::Normal;
            $dWkToFill = array('lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi'); 
            
            foreach ($dWkToFill  as $d ):
                $dataHor[$d]  =  true;
                $dataHor[$d.'_ouverture']  = '07:00';
                $dataHor[$d.'_fermeture']  = '23:00';
            endforeach ;
            
            $hor        = new SiteHoraire($dataHor);
            $horTbl->save($hor);
            
            //retrieving
            $horaire = $horTbl->getBySite($site->id);
        }
	
	// Horaire Congé
	$congeH = $horTbl->getBySite($site->id, \RHX\Model\Object\SiteHoraireType::Conge);
	if(!$congeH){
	    $dataHor = array();
	    $dataHor['site_id']  = $site->id;
	    $dataHor['type']  = \RHX\Model\Object\SiteHoraireType::Conge;
            $dWkToFill = array('lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi');
	    foreach ($dWkToFill  as $d ):
                $dataHor[$d]  =  true;
                $dataHor[$d.'_ouverture']  = '07:00';
                $dataHor[$d.'_fermeture']  = '23:00';
            endforeach ;
	    $congeH = new SiteHoraire($dataHor);
	    $congeH->id = $horTbl->save($congeH);
	}
	
	// Exceptionnel
	$exceptionelH = $horTbl->getBySite($site->id, \RHX\Model\Object\SiteHoraireType::Exceptionnel);
	if(!$exceptionelH){
	    $dataHor = array();
	    $dataHor['site_id']  = $site->id;
	    $dataHor['type']  = \RHX\Model\Object\SiteHoraireType::Exceptionnel;
            $dWkToFill = array('lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi');
	    foreach ($dWkToFill  as $d ):
                $dataHor[$d]  =  true;
                $dataHor[$d.'_ouverture']  = '07:00';
                $dataHor[$d.'_fermeture']  = '23:00';
            endforeach ;
	    $exceptionelH = new SiteHoraire($dataHor);
	    $exceptionelH->id = $horTbl->save($exceptionelH);
	}
	
        $ret['rep_upload'] = $repUpload;	
        $ret['site'] = $site;
        $ret['siteManager'] = $siteManager;
        $ret['horaire'] = $horaire;
	$ret['conge'] = $congeH;
	$ret['exceptionnel'] = $exceptionelH;
        
        /* // nb d'employés        
        $ret['nb_employe'] = count($empTable->getEmployesBySiteEx2($idSite));
        var_dump($ret['nb_employe'] );*/
        
        return $ret;	
    }
    /**
     * rendu de la page d'ajout d'un site
     *
     * @return array
     */
     public function addAction() {
        $query = $this->getRequest();
        $ret = array();
        
        
        $dWkToFill = array('lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi'); 
        $dataHor['id']  =  0;
        $dataHor['site_id']  =  0;
        foreach ($dWkToFill  as $d ):
            $dataHor[$d]  =  true;
            $dataHor[$d.'_ouverture']  = '07:00';
            $dataHor[$d.'_fermeture']  = '23:00';
        endforeach ;
        $horaire        = new SiteHoraire($dataHor);
        $ret['horaire'] = $horaire;
        //var_dump($horaire); die;
        return $ret;	
    }
    
    /**
     * Téléchargement du photo du site
     *
     * @return array
     */
    public function uploadPhotoAction() {
        $this->layout('layout/iframe2');
        $query = $this->getRequest();
        
        // tables         
        $siteTable = $this->getService('Table\SiteTable');
        
        if ($query->isPost()) {
            $post = $query->getPost();
            $config = $this->getServiceLocator()->get('config');
            
            $idSite = (int) $post->site_id;
            
            if ($idSite !== -1)                
                $site = $siteTable->get($idSite);
            else
                $site = null;
            
            $random = rand();
            
            $dir = $config['upload_directory']['site']['photo'];
            
            $name = $dir.$random. ".jpg";
            // Téléchargement du fichier PHOTO
            $extensions = array('jpg', 'png', 'gif');
            $result = Uploader::upload('photo', $name, FALSE, $extensions );
            $result['destination'] = "$random.jpg";
            
             if ($result['done']) {
                //echo "<pre>DONE = true</pre>";                
                
                if ($idSite > 0) {
                    // Mise à jour des données
                    $newName  = $dir. 'photo-' . $idSite . '.' . $result['extension'];
                    $newName2 = str_replace('public/', '', $newName);
                    // renommer fichier
                    if (@rename($name, $newName) || @rename($name, $newName2)) {
                        $result['destination'] = 'photo-' . $idSite . '.' . $result['extension'];
                    }
                }
                return array(             
                    'site' => $site,
                    'fichier' => $result['name'],
                    'dir_photo' =>   $dir,
                    'destination' => $result['destination'],
                    'extension' => $result['extension'],
                    'error' => $result['error'],
                );
            }
            elseif( $result['error'] ){
                 return array(
                    'site' => $site,
                    'fichier' => null,                    
                    'error' => $result['error'],                    
                );
            }
        }
        
        //get         
        $idSite = (int) $this->params()->fromRoute('id', -1);        
        
        //new site
        if($idSite == -1){
            return array(
            'site' => null,
            'newSite' => true,
            'fichier' => null,
            );
        }
        //site existant
        $site = $siteTable->get($idSite);
        
        return array(
            'site' => $site,
            'fichier' => null,
        );
	
    }
    /**
     * Téléchargement du rib du site
     *
     * @return array
     */
    public function uploadRibAction() {
        $this->layout('layout/iframe2');
        $query = $this->getRequest();
        
        // tables         
        $siteTable = $this->getService('Table\SiteTable');
        
        //POST 
        if ($query->isPost()) {
            $post = $query->getPost();
            $config = $this->getServiceLocator()->get('config');  
            
            $idSite = (int) $post->site_id;
            
            if ($idSite !== -1)                
                $site = $siteTable->get($idSite);
            else
                $site = null;
            
            $random = rand();
            
            $dir = $config['upload_directory']['site']['rib'];
            //$name = "public/upload/site/rib/$random.jpg"; // pattern
            $name = $dir. $random.".jpg";
            
            // Téléchargement du fichier RIB
            $extensions = array('pdf', 'jpg', 'png', 'gif', 'docx');
            $result = Uploader::upload('rib', $name, FALSE, $extensions );
            $result['destination'] = "$random.jpg";
            
             if ($result['done']) {
                //echo "<pre>DONE = true</pre>";                
                
                if ($idSite > 0) {
                    // Mise à jour des données
                    $newName = $dir .'rib-' . $idSite . '.' . $result['extension'];
                    $newName2 = str_replace('public/', '', $newName);
                    // renommer fichier
                    if (@rename($name, $newName) || @rename($name, $newName2)) {
                        $result['destination'] = 'rib-' . $idSite . '.' . $result['extension'];
                    }
                }
                return array(             
                    'site' => $site,
                    'fichier' => $result['name'],
                    'dir_rib' =>  $dir,
                    'destination' => $result['destination'],
                    'extension' => $result['extension'],
                    'error' => $result['error'],
                );
            }
            elseif( $result['error'] ){
                 return array(
                    'site' => $site,
                    'fichier' => null,                    
                    'error' => $result['error'],                    
                );
            }
        }
        
        //GET
        
        $idSite = (int) $this->params()->fromRoute('id', -1);        
        // get new site
        if($idSite == -1){
            return array(
            'site' => null,
            'newSite' => true,
            'fichier' => null,
            );
        }
        
        //get site existant
        $site = $siteTable->get($idSite);
        return array(
            'site' => $site,
            'fichier' => null,
        );
	
    }
    
    /**
     * Liste des documents pour un site
     * 
     * @return array
     */
    public function docListAction(){        
        // manager 
        $siteManager = new \RHX\Model\Manager\SiteManager($this->getAdapter());         
        $fileManager = new \RHX\Model\Manager\FileManager($this->getAdapter()) ;
        
        // tables        
        $siteTable      = $this->getService('Table\SiteTable');
        $siteDocTable   = $this->getService('Table\SiteDocTable');
        
        //params
	$post = $this->getPost();
        $idSite = $post->site;
        
	$this->layout('layout/ajax');
        $site   = $siteTable->get($idSite);
        
	$listDoc = $siteDocTable->getBySite($site->id);
        
	return array(
	    'listDoc' => $listDoc,
            'fileManager' => $fileManager,
            'site' => $site,
            'siteManager' => $siteManager
	);
    }
    
    /* Sauvegarder le nom des documents 
     */
    function saveDocumentAction(){
        // Changement de layout
	$this->layout('layout/ajax');
        
        // manager  & tables 
        $siteManager = new \RHX\Model\Manager\SiteManager($this->getAdapter());
        $fileManager = new \RHX\Model\Manager\FileManager($this->getAdapter());             
            $fileManager->setFlag(\RHX\Model\Manager\FileManager::SITE_DOC_FILE);
        $siteDocTable   = $this->getService('Table\SiteDocTable');

	// Données en POST
	$post = $this->getRequest()->getPost();

	// Variables	
	//$name	 = $post->name;
        $data['site_id'] = $siteId = $post->pk;
        $data['path']    = $path = addslashes($post->value);
        
        $siteDoc = new SiteDoc($this->getAdapter(), $data );
        
        $maxId = $siteDocTable->getMaxId();
        $pathInfo = pathinfo($path);
        
	//renommer le fichier physique
        $new_path = $fileManager->renameFile(array(
                                                    'format' => array($siteId, $maxId + 1), 
                                                    'extension' => $pathInfo['extension']
                                                  ),
                                             $path
                                             );
        //renommer le path de l'objet
        $siteDoc->path = $new_path;
        
        //sauvegarde
        $idNew = $siteDocTable->save($siteDoc); 
        $siteDoc->id = $idNew;
        
        return new JsonModel(array(
            'success' => true,
            'nbCountDoc' => $siteManager->getCountDoc($siteId)
            ));
        
    }
    /* Suppresion d' un document
     * 
     */
    public function eraseDocumentAction(){
        // Changement de layout
	$this->layout('layout/ajax');
        
        // Données en POST
	$post = $this->getRequest()->getPost();
        
        // manager  & tables 
        $siteManager = new \RHX\Model\Manager\SiteManager($this->getAdapter());                 
        $siteDocTable   = $this->getService('Table\SiteDocTable');
        
        $siteDocTable->erase($post->id);
        
        return new JsonModel(array(
            'success' => true,
            'nbCountDoc' => $siteManager->getCountDoc($post->site)
            ));
        
    }
    
    /*
     */
    public function updateDocumentAction(){
        //layout ajax
        $this->layout('layout/ajax');
        
        //donnés post
        $post = $this->getRequest()->getPost();
        
        //tables
        $siteDocTable   = $this->getService('Table\SiteDocTable');
        
        $pk = $post->get('pk');
        $name = $post->get('name');
        $value = $post->get('value');

        $value = addslashes($value);

        $sql = "UPDATE rh_site_doc SET $name = '$value' WHERE id = $pk";
        $result = $siteDocTable->executeQuery($sql);

        return array(
            'sql' => $sql,
            'result' => $result,
        );
    }
    
    /**
     * Liste des premiers mois
     * 
     * @return \Zend\View\Model\JsonModel
     */
    public function dateTransfertAction(){
	$date = new \DateTime();
	$array = array();
	for($i = 0; $i < 5; $i++){
	    $date->modify('next month');
	    $date->setDate((int)$date->format('Y'), (int)$date->format('m'), 1);
	    $dateAffichage = new \RHX\Helper\RHDateTime($date->format('Y-m-d'));
	    $array[$dateAffichage->date()] = $dateAffichage->dateFr();
	}
	return new JsonModel($array);
    }
}
